# -*- coding: utf-8 -*-
import threading

import zmq

from global_data.glabal_data import GlobalData

"""
实现zmq代理转发模式
server通过connect命令连接到 XSUB，可发送信息到sub，通过代理转发出去
client通过connect命令连接到 XPUB，可订阅不同的server发送的消息
"""


class ZmqXProxy:
    def __init__(self, xpub_ip=None, xpub_port=None, xsub_ip=None, xsub_port=None):
        self.my_thread = None
        self.ctx = None
        self.xpub_sock = None
        self.xsub_sock = None
        self.xpub_url = f'tcp://{GlobalData.ZMQ_XPUB_IP if xpub_ip is None else xpub_ip}:{GlobalData.ZMQ_XPUB_PORT if xpub_port is None else xpub_port}'
        self.xsub_url = f'tcp://{GlobalData.ZMQ_XSUB_IP if xsub_ip is None else xsub_ip}:{GlobalData.ZMQ_XSUB_PORT if xsub_port is None else xsub_port}'

    def stop(self):
        self.xpub_sock.close()
        self.xsub_sock.close()
        self.ctx.term()
        self.ctx.destroy()

    def run(self):
        self.ctx = zmq.Context()
        self.xpub_sock = self.ctx.socket(zmq.XPUB)
        self.xpub_sock.bind(self.xpub_url)
        self.xsub_sock = self.ctx.socket(zmq.XSUB)
        self.xsub_sock.bind(self.xsub_url)
        # 二选一
        # 方法一   自动处理转发
        zmq.proxy(self.xpub_sock, self.xsub_sock, None)
        # 方法二   可以自定义消息
        # poller = zmq.Poller()
        # poller.register(self.xpub_sock, zmq.POLLIN)
        # poller.register(self.xsub_sock, zmq.POLLIN)
        # while True:
        #     socks = dict(poller.poll())
        #     if self.xpub_sock in socks and socks[self.xpub_sock] == zmq.POLLIN:
        #         msg = self.xpub_sock.recv_multipart()
        #         self.xsub_sock.send_multipart(msg)
        #     elif self.xsub_sock in socks and socks[self.xsub_sock] == zmq.POLLIN:
        #         msg = self.xsub_sock.recv_multipart()
        #         self.xpub_sock.send_multipart(msg)
        # 获取事件
        pub_events = self.xpub_sock.getsockopt(zmq.EVENTS, 0)
        
        # 检查是否有新的订阅者接入
        if pub_events & zmq.POLL_IN:
            # 有新的订阅者接入
            print("接入，，，，，，，，，，，")
            pass

    def start(self):
        self.my_thread = threading.Thread(target=self.run, kwargs={})
        self.my_thread.setDaemon(True)
        self.my_thread.start()
        return self.my_thread

    def stop(self):
        self.my_thread.stop()


if __name__ == "__main__":
    pass
